<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><title>MySQL索引优化 | Kylin</title><meta name="keywords" content="数据库,MySQL"><meta name="author" content="Kylin"><meta name="copyright" content="Kylin"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="环境搭建建表语句123456789101112131415161718 CREATE TABLE &#96;dept&#96; ( &#96;id&#96; INT(11) NOT NULL AUTO_INCREMENT, &#96;deptName&#96; VARCHAR(30) DEFAULT NULL, &#96;address&#96; VARCHAR(40) DEFAULT NULL, ceo INT NULL , PRIMARY KEY (&#96;id">
<meta property="og:type" content="article">
<meta property="og:title" content="MySQL索引优化">
<meta property="og:url" content="https://www.codekylin.cn/24797.html">
<meta property="og:site_name" content="Kylin">
<meta property="og:description" content="环境搭建建表语句123456789101112131415161718 CREATE TABLE &#96;dept&#96; ( &#96;id&#96; INT(11) NOT NULL AUTO_INCREMENT, &#96;deptName&#96; VARCHAR(30) DEFAULT NULL, &#96;address&#96; VARCHAR(40) DEFAULT NULL, ceo INT NULL , PRIMARY KEY (&#96;id">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://qiniu.codekylin.cn/github/img/img/code1.jpg">
<meta property="article:published_time" content="2020-10-26T07:43:38.000Z">
<meta property="article:modified_time" content="2022-07-12T11:42:50.023Z">
<meta property="article:author" content="Kylin">
<meta property="article:tag" content="数据库">
<meta property="article:tag" content="MySQL">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://qiniu.codekylin.cn/github/img/img/code1.jpg"><link rel="shortcut icon" href="https://qiniu.codekylin.cn/img/20200807181548.png"><link rel="canonical" href="https://www.codekylin.cn/24797"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//www.google-analytics.com" crossorigin=""/><link rel="preconnect" href="//hm.baidu.com"/><link rel="preconnect" href="//fonts.googleapis.com" crossorigin=""/><meta name="google-site-verification" content="gzeyWstt6NoTZKh7YFYNLNziL8HIZ8YH2Ug7xTDX5-Y"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.css" media="print" onload="this.media='all'"><script>var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "https://hm.baidu.com/hm.js?f76c34daefe747deee7c7be3ead2ba80";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();
</script><script async="async" src="https://www.googletagmanager.com/gtag/js?id=UA-159334016-1"></script><script>window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-159334016-1');
</script><link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Titillium+Web" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"search.xml","languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"简"},
  noticeOutdate: {"limitDay":90,"position":"top","messagePrev":"自上次更新以来已经","messageNext":"天，文章的内容可能已过时或存在差异。"},
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: {"limitCount":50000,"languages":{"author":"作者: Kylin","link":"链接: ","source":"来源: Kylin","info":"著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。"}},
  lightbox: 'fancybox',
  Snackbar: {"chs_to_cht":"你已切换为繁体","cht_to_chs":"你已切换为简体","day_to_night":"你已切换为深色模式","night_to_day":"你已切换为浅色模式","bgLight":"#FF0000","bgDark":"#2d3035","position":"bottom-left"},
  source: {
    jQuery: 'https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js',
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/js/jquery.justifiedGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/css/justifiedGallery.min.css'
    },
    fancybox: {
      js: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js',
      css: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: true,
  isanchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = { 
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2022-07-12 19:42:50'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          const isDarkMode = window.matchMedia('(prefers-color-scheme: dark)').matches
          const isLightMode = window.matchMedia('(prefers-color-scheme: light)').matches
          const isNotSpecified = window.matchMedia('(prefers-color-scheme: no-preference)').matches
          const hasNoSupport = !isDarkMode && !isLightMode && !isNotSpecified

          if (t === undefined) {
            if (isLightMode) activateLightMode()
            else if (isDarkMode) activateDarkMode()
            else if (isNotSpecified || hasNoSupport) {
              const now = new Date()
              const hour = now.getHours()
              const isNight = hour <= 6 || hour >= 18
              isNight ? activateDarkMode() : activateLightMode()
            }
            window.matchMedia('(prefers-color-scheme: dark)').addListener(function (e) {
              if (saveToLocal.get('theme') === undefined) {
                e.matches ? activateDarkMode() : activateLightMode()
              }
            })
          } else if (t === 'light') activateLightMode()
          else activateDarkMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const fontSizeVal = saveToLocal.get('global-font-size')
    if (fontSizeVal !== undefined) {
      document.documentElement.style.setProperty('--global-font-size', fontSizeVal + 'px')
    }
    })(window)</script><link rel="stylesheet" href="https://qiniu.codekylin.cn/github/img/img/custom.css"><link rel="stylesheet" href="//at.alicdn.com/t/font_1993646_z05rabxf05h.css"><link rel="stylesheet" href="https://qiniu.codekylin.cn/github/img/img/icon.css"><meta name="generator" content="Hexo 5.4.0"><link rel="alternate" href="/atom.xml" title="Kylin" type="application/atom+xml">
</head><body><div id="web_bg"></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="author-avatar"><img class="avatar-img" data-lazy-src="https://qiniu.codekylin.cn/img/20200807181526.jpg" onerror="onerror=null;src='https://qiniu.codekylin.cn/github/img/friend_404.gif'" alt="avatar"/></div><div class="site-data"><div class="data-item is-center"><div class="data-item-link"><a href="/archives/"><div class="headline">文章</div><div class="length-num">362</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/tags/"><div class="headline">标签</div><div class="length-num">427</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/categories/"><div class="headline">分类</div><div class="length-num">101</div></a></div></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fa fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fa fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fa fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fa fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fa fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fa fa-heart"></i><span> 关于</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://qiniu.codekylin.cn/github/img/img/code1.jpg')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">Kylin</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fa fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fa fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fa fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fa fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fa fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fa fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">MySQL索引优化</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2020-10-26T07:43:38.000Z" title="发表于 2020-10-26 15:43:38">2020-10-26</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2022-07-12T11:42:50.023Z" title="更新于 2022-07-12 19:42:50">2022-07-12</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/%E6%95%B0%E6%8D%AE%E5%BA%93/">数据库</a><i class="fas fa-angle-right post-meta-separator"></i><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/%E6%95%B0%E6%8D%AE%E5%BA%93/MySQL/">MySQL</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">4.5k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>18分钟</span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h2 id="环境搭建"><a href="#环境搭建" class="headerlink" title="环境搭建"></a>环境搭建</h2><h3 id="建表语句"><a href="#建表语句" class="headerlink" title="建表语句"></a>建表语句</h3><figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"> <span class="keyword">CREATE</span> <span class="keyword">TABLE</span> `dept` (</span><br><span class="line"> `id` <span class="type">INT</span>(<span class="number">11</span>) <span class="keyword">NOT</span> <span class="keyword">NULL</span> AUTO_INCREMENT,</span><br><span class="line"> `deptName` <span class="type">VARCHAR</span>(<span class="number">30</span>) <span class="keyword">DEFAULT</span> <span class="keyword">NULL</span>,</span><br><span class="line"> `address` <span class="type">VARCHAR</span>(<span class="number">40</span>) <span class="keyword">DEFAULT</span> <span class="keyword">NULL</span>,</span><br><span class="line"> ceo <span class="type">INT</span> <span class="keyword">NULL</span> ,</span><br><span class="line"> <span class="keyword">PRIMARY</span> KEY (`id`)</span><br><span class="line">) ENGINE<span class="operator">=</span>INNODB AUTO_INCREMENT<span class="operator">=</span><span class="number">1</span> <span class="keyword">DEFAULT</span> CHARSET<span class="operator">=</span>utf8;</span><br><span class="line"> </span><br><span class="line"><span class="keyword">CREATE</span> <span class="keyword">TABLE</span> `emp` (</span><br><span class="line"> `id` <span class="type">INT</span>(<span class="number">11</span>) <span class="keyword">NOT</span> <span class="keyword">NULL</span> AUTO_INCREMENT,</span><br><span class="line"> `empno` <span class="type">INT</span> <span class="keyword">NOT</span> <span class="keyword">NULL</span> ,</span><br><span class="line"> `name` <span class="type">VARCHAR</span>(<span class="number">20</span>) <span class="keyword">DEFAULT</span> <span class="keyword">NULL</span>,</span><br><span class="line"> `age` <span class="type">INT</span>(<span class="number">3</span>) <span class="keyword">DEFAULT</span> <span class="keyword">NULL</span>,</span><br><span class="line"> `deptId` <span class="type">INT</span>(<span class="number">11</span>) <span class="keyword">DEFAULT</span> <span class="keyword">NULL</span>,</span><br><span class="line"> <span class="keyword">PRIMARY</span> KEY (`id`)</span><br><span class="line"> #<span class="keyword">CONSTRAINT</span> `fk_dept_id` <span class="keyword">FOREIGN</span> KEY (`deptId`) <span class="keyword">REFERENCES</span> `t_dept` (`id`)</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="创建函数"><a href="#创建函数" class="headerlink" title="创建函数"></a>创建函数</h3><p>创建函数，假如报错：<code>This function has none of DETERMINISTIC......</code></p>
<p>由于开启过慢查询日志，因为我们开启了 bin-log, 我们就必须为我们的function指定一个参数。</p>
<ul>
<li>show variables like ‘log_bin_trust_function_creators’;</li>
<li>set global log_bin_trust_function_creators=1;</li>
</ul>
<p><strong>随机产生字符串</strong></p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">DELIMITER $$</span><br><span class="line"><span class="keyword">CREATE</span> <span class="keyword">FUNCTION</span> rand_string(n <span class="type">INT</span>) <span class="keyword">RETURNS</span> <span class="type">VARCHAR</span>(<span class="number">255</span>)</span><br><span class="line"><span class="keyword">BEGIN</span>    </span><br><span class="line">	 <span class="keyword">DECLARE</span> chars_str <span class="type">VARCHAR</span>(<span class="number">100</span>) <span class="keyword">DEFAULT</span> <span class="string">&#x27;abcdefghijklmnopqrstuvwxyzABCDEFJHIJKLMNOPQRSTUVWXYZ&#x27;</span>;</span><br><span class="line">	 <span class="keyword">DECLARE</span> return_str <span class="type">VARCHAR</span>(<span class="number">255</span>) <span class="keyword">DEFAULT</span> <span class="string">&#x27;&#x27;</span>;</span><br><span class="line">	 <span class="keyword">DECLARE</span> i <span class="type">INT</span> <span class="keyword">DEFAULT</span> <span class="number">0</span>;</span><br><span class="line">	 WHILE i <span class="operator">&lt;</span> n DO</span><br><span class="line">		 <span class="keyword">SET</span> return_str <span class="operator">=</span>CONCAT(return_str,<span class="built_in">SUBSTRING</span>(chars_str,<span class="built_in">FLOOR</span>(<span class="number">1</span><span class="operator">+</span>RAND()<span class="operator">*</span><span class="number">52</span>),<span class="number">1</span>));</span><br><span class="line">		 <span class="keyword">SET</span> i <span class="operator">=</span> i <span class="operator">+</span> <span class="number">1</span>;</span><br><span class="line">	 <span class="keyword">END</span> WHILE;</span><br><span class="line">	 <span class="keyword">RETURN</span> return_str;</span><br><span class="line"><span class="keyword">END</span> $$</span><br><span class="line">#假如要删除</span><br><span class="line">#<span class="keyword">drop</span> <span class="keyword">function</span> rand_string;</span><br></pre></td></tr></table></figure>

<p><strong>随机产生部门编号</strong></p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">#用于随机产生多少到多少的编号</span><br><span class="line">DELIMITER $$</span><br><span class="line"><span class="keyword">CREATE</span> <span class="keyword">FUNCTION</span>  rand_num (from_num <span class="type">INT</span> ,to_num <span class="type">INT</span>) <span class="keyword">RETURNS</span> <span class="type">INT</span>(<span class="number">11</span>)</span><br><span class="line"><span class="keyword">BEGIN</span>   </span><br><span class="line">	<span class="keyword">DECLARE</span> i <span class="type">INT</span> <span class="keyword">DEFAULT</span> <span class="number">0</span>;  </span><br><span class="line">	<span class="keyword">SET</span> i <span class="operator">=</span> <span class="built_in">FLOOR</span>(from_num <span class="operator">+</span>RAND()<span class="operator">*</span>(to_num <span class="operator">-</span>from_num<span class="operator">+</span><span class="number">1</span>));</span><br><span class="line"><span class="keyword">RETURN</span> i;  </span><br><span class="line"><span class="keyword">END</span>$$ </span><br><span class="line">#假如要删除</span><br><span class="line">#<span class="keyword">drop</span> <span class="keyword">function</span> rand_num;</span><br><span class="line"> </span><br><span class="line"><span class="keyword">SELECT</span> rand_num(<span class="number">50</span>,<span class="number">100</span>);</span><br></pre></td></tr></table></figure>

<h3 id="创建调用存储过程"><a href="#创建调用存储过程" class="headerlink" title="创建调用存储过程"></a>创建调用存储过程</h3><p><strong>往emp表中插入数据</strong></p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">DELIMITER $$</span><br><span class="line"><span class="keyword">CREATE</span> <span class="keyword">PROCEDURE</span> insert_emp(<span class="keyword">START</span> <span class="type">INT</span>, max_num <span class="type">INT</span>)</span><br><span class="line"><span class="keyword">BEGIN</span>  </span><br><span class="line">	<span class="keyword">DECLARE</span> i <span class="type">INT</span> <span class="keyword">DEFAULT</span> <span class="number">0</span>;   </span><br><span class="line">	#<span class="keyword">set</span> autocommit <span class="operator">=</span><span class="number">0</span> 把autocommit设置成<span class="number">0</span>  </span><br><span class="line">	<span class="keyword">SET</span> autocommit <span class="operator">=</span> <span class="number">0</span>;   </span><br><span class="line">		REPEAT  </span><br><span class="line">			<span class="keyword">SET</span> i <span class="operator">=</span> i <span class="operator">+</span> <span class="number">1</span>;  </span><br><span class="line">			<span class="keyword">INSERT</span> <span class="keyword">INTO</span> emp (empno, NAME ,age ,deptid ) <span class="keyword">VALUES</span> ((<span class="keyword">START</span><span class="operator">+</span>i) ,rand_string(<span class="number">6</span>), rand_num(<span class="number">30</span>,<span class="number">50</span>),rand_num(<span class="number">1</span>,<span class="number">10000</span>));  </span><br><span class="line">			UNTIL i <span class="operator">=</span> max_num  </span><br><span class="line">		<span class="keyword">END</span> REPEAT; </span><br><span class="line">	<span class="keyword">COMMIT</span>;  </span><br><span class="line"><span class="keyword">END</span>$$</span><br><span class="line">#删除</span><br><span class="line"># DELIMITER ;</span><br><span class="line"># <span class="keyword">drop</span> <span class="keyword">PROCEDURE</span> insert_emp;</span><br><span class="line"> </span><br><span class="line">#执行存储过程，往emp表添加<span class="number">50</span>万条数据</span><br><span class="line">DELIMITER ;</span><br><span class="line"><span class="keyword">CALL</span> insert_emp(<span class="number">100000</span>,<span class="number">500000</span>); </span><br></pre></td></tr></table></figure>

<p><strong>往dept表中插入数据</strong></p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">#执行存储过程，往dept表添加随机数据</span><br><span class="line">DELIMITER $$</span><br><span class="line"><span class="keyword">CREATE</span> <span class="keyword">PROCEDURE</span> `insert_dept`(max_num <span class="type">INT</span>)</span><br><span class="line">	<span class="keyword">BEGIN</span>  </span><br><span class="line">	<span class="keyword">DECLARE</span> i <span class="type">INT</span> <span class="keyword">DEFAULT</span> <span class="number">0</span>;   </span><br><span class="line">	<span class="keyword">SET</span> autocommit <span class="operator">=</span> <span class="number">0</span>;    </span><br><span class="line">		REPEAT  </span><br><span class="line">			<span class="keyword">SET</span> i <span class="operator">=</span> i <span class="operator">+</span> <span class="number">1</span>;  </span><br><span class="line">			<span class="keyword">INSERT</span> <span class="keyword">INTO</span> dept ( deptname,address,ceo ) <span class="keyword">VALUES</span> (rand_string(<span class="number">8</span>),rand_string(<span class="number">10</span>),rand_num(<span class="number">1</span>,<span class="number">500000</span>));  </span><br><span class="line">			UNTIL i <span class="operator">=</span> max_num  </span><br><span class="line">		<span class="keyword">END</span> REPEAT;  </span><br><span class="line">	<span class="keyword">COMMIT</span>;  </span><br><span class="line"><span class="keyword">END</span>$$</span><br><span class="line">#删除</span><br><span class="line"># DELIMITER ;</span><br><span class="line"># <span class="keyword">drop</span> <span class="keyword">PROCEDURE</span> insert_dept;</span><br><span class="line"> </span><br><span class="line">#执行存储过程，往dept表添加<span class="number">1</span>万条数据</span><br><span class="line">DELIMITER ;</span><br><span class="line"><span class="keyword">CALL</span> insert_dept(<span class="number">10000</span>); </span><br></pre></td></tr></table></figure>

<h3 id="删除索引"><a href="#删除索引" class="headerlink" title="删除索引"></a>删除索引</h3><p><strong>删除指定数据库中表除主键索引之外的所有索引。</strong></p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line">DELIMITER $$</span><br><span class="line"><span class="keyword">CREATE</span> <span class="keyword">PROCEDURE</span> `proc_drop_index`(dbname <span class="type">VARCHAR</span>(<span class="number">200</span>),tablename <span class="type">VARCHAR</span>(<span class="number">200</span>))</span><br><span class="line"><span class="keyword">BEGIN</span></span><br><span class="line">	<span class="keyword">DECLARE</span> done <span class="type">INT</span> <span class="keyword">DEFAULT</span> <span class="number">0</span>;</span><br><span class="line">	<span class="keyword">DECLARE</span> ct <span class="type">INT</span> <span class="keyword">DEFAULT</span> <span class="number">0</span>;</span><br><span class="line">	<span class="keyword">DECLARE</span> _index <span class="type">VARCHAR</span>(<span class="number">200</span>) <span class="keyword">DEFAULT</span> <span class="string">&#x27;&#x27;</span>;</span><br><span class="line">	<span class="keyword">DECLARE</span> _cur <span class="keyword">CURSOR</span> <span class="keyword">FOR</span> <span class="keyword">SELECT</span> index_name <span class="keyword">FROM</span> information_schema.STATISTICS   <span class="keyword">WHERE</span> table_schema<span class="operator">=</span>dbname <span class="keyword">AND</span> table_name<span class="operator">=</span>tablename <span class="keyword">AND</span> seq_in_index<span class="operator">=</span><span class="number">1</span> <span class="keyword">AND</span> index_name<span class="operator">&lt;&gt;</span><span class="string">&#x27;PRIMARY&#x27;</span> ;</span><br><span class="line">	<span class="keyword">DECLARE</span> CONTINUE HANDLER <span class="keyword">FOR</span> <span class="keyword">NOT</span> FOUND <span class="keyword">set</span> done<span class="operator">=</span><span class="number">2</span>;</span><br><span class="line">	<span class="keyword">OPEN</span> _cur;</span><br><span class="line">		<span class="keyword">FETCH</span> _cur <span class="keyword">INTO</span> _index;</span><br><span class="line">		WHILE _index<span class="operator">&lt;&gt;</span><span class="string">&#x27;&#x27;</span> DO </span><br><span class="line">			<span class="keyword">SET</span> <span class="variable">@str</span> <span class="operator">=</span> CONCAT(&quot;drop index &quot;,_index,&quot; on &quot;,tablename );</span><br><span class="line">			<span class="keyword">PREPARE</span> sql_str <span class="keyword">FROM</span> <span class="variable">@str</span> ;</span><br><span class="line">			<span class="keyword">EXECUTE</span>  sql_str;</span><br><span class="line">			<span class="keyword">DEALLOCATE</span> <span class="keyword">PREPARE</span> sql_str;</span><br><span class="line">			<span class="keyword">SET</span> _index<span class="operator">=</span><span class="string">&#x27;&#x27;</span>; </span><br><span class="line">			<span class="keyword">FETCH</span> _cur <span class="keyword">INTO</span> _index; </span><br><span class="line">		<span class="keyword">END</span> WHILE;</span><br><span class="line">	<span class="keyword">CLOSE</span> _cur;</span><br><span class="line"><span class="keyword">END</span>$$</span><br><span class="line"> </span><br><span class="line">#<span class="keyword">CALL</span> proc_drop_index(&quot;dbname&quot;,&quot;tablename&quot;);</span><br></pre></td></tr></table></figure>

<h2 id="单表使用索引及常见索引失效"><a href="#单表使用索引及常见索引失效" class="headerlink" title="单表使用索引及常见索引失效"></a>单表使用索引及常见索引失效</h2><h3 id="案例"><a href="#案例" class="headerlink" title="案例"></a>案例</h3><p><strong>全值匹配</strong></p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20201026160746.png" alt="image-20201026160742069"></p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20201026160820.png" alt="image-20201026160818953"></p>
<p>添加使用索引<code>CREATE INDEX idx_age ON emp(age);</code></p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20201026160932.png" alt="image-20201026160930866"></p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20201026161013.png" alt="image-20201026161012521"></p>
<p>起到了优化效果。删除相关索引。<code>CALL proc_drop_index(&quot;mydb&quot;,&quot;emp&quot;);</code></p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20201026161141.png" alt="image-20201026161140190"></p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20201026161200.png" alt="image-20201026161158790"></p>
<p>添加索引<code>CREATE INDEX idx_age_deptid ON emp(age,deptid);</code></p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20201026161244.png" alt="image-20201026161243195"></p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20201026161323.png" alt="image-20201026161321021"></p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20201026161337.png" alt="image-20201026161336661"></p>
<p>查询时间大幅度减少到0.001!!删除相关索引。<code>CALL proc_drop_index(&quot;mydb&quot;,&quot;emp&quot;);</code></p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20201026161510.png" alt="image-20201026161508829"></p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20201026161544.png" alt="image-20201026161543116"></p>
<p>建立索引<code>CREATE INDEX idx_age_deptid_name ON emp(age,deptid,name);</code></p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20201026161621.png" alt="image-20201026161619566"></p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20201026161646.png" alt="image-20201026161645337"></p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20201026161702.png" alt="image-20201026161701444"></p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">EXPLAIN <span class="keyword">SELECT</span> SQL_NO_CACHE <span class="operator">*</span> <span class="keyword">FROM</span> emp <span class="keyword">WHERE</span> emp.age <span class="operator">=</span> <span class="number">30</span>;</span><br><span class="line"><span class="keyword">CREATE</span> INDEX idx_age <span class="keyword">ON</span> emp(age);</span><br><span class="line"></span><br><span class="line">EXPLAIN <span class="keyword">SELECT</span> SQL_NO_CACHE <span class="operator">*</span> <span class="keyword">FROM</span> emp <span class="keyword">WHERE</span> emp.age <span class="operator">=</span> <span class="number">30</span> <span class="keyword">AND</span> deptid <span class="operator">=</span> <span class="number">4</span>;</span><br><span class="line"><span class="keyword">CREATE</span> INDEX idx_age_deptid <span class="keyword">ON</span> emp(age,deptid);</span><br><span class="line"></span><br><span class="line">EXPLAIN <span class="keyword">SELECT</span> SQL_NO_CACHE <span class="operator">*</span> <span class="keyword">FROM</span> emp <span class="keyword">WHERE</span> emp.age <span class="operator">=</span> <span class="number">30</span> <span class="keyword">AND</span> deptid <span class="operator">=</span> <span class="number">4</span> <span class="keyword">AND</span> emp.`name` <span class="operator">=</span> <span class="string">&#x27;abcd&#x27;</span>;</span><br><span class="line"><span class="keyword">CREATE</span> INDEX idx_age_deptid_name <span class="keyword">ON</span> emp(age,deptid,name);</span><br></pre></td></tr></table></figure>

<p><strong>最佳左前缀法则</strong></p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20201026204618.png" alt="image-20201026204615717"></p>
<p>将三个条件调换顺序依旧能是复合索引生效！这是因为mysql优化器把我们的sql给自动优化调整顺序了。</p>
<p>将<code>age</code>条件放到最前后面接着<code>name</code>条件</p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20201026204715.png" alt="image-20201026204713979"></p>
<p>却发现此时的<code>key_len=5</code>也就是只有age索引生效啦！再次改变</p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20201026204906.png" alt="image-20201026204905702"></p>
<p>复合索引全部失效！！</p>
<p>这是为什么呢？这就是因为<strong>最佳左前缀法则</strong></p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20201026221344.png" alt="image-20201026204005730"></p>
<p>第一种情况mysql优化器把三种情况给优化了所以条件依旧为<code>age</code>,<code>deptid</code>,<code>name</code></p>
<p>第二种情况条件为<code>age</code>,<code>name</code>缺少了<code>deptid</code>，所以不能找到<code>name</code>。也就只有<code>age</code>生效</p>
<p>第三种情况条件为<code>deptid</code>,<code>name</code>因为缺少了<code>age</code>所以根本无法进行查找。全部失效</p>
<p><strong><mark>如果索引了多列，要遵守最左前缀法则。指的是查询从索引的最左前列开始并且不跳过索引中的列。</mark></strong></p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">## 最佳左前缀法则</span><br><span class="line"><span class="keyword">CREATE</span> INDEX idx_age_deptid_name <span class="keyword">ON</span> emp(age,deptid,name);</span><br><span class="line"></span><br><span class="line">EXPLAIN <span class="keyword">SELECT</span> SQL_NO_CACHE <span class="operator">*</span> <span class="keyword">FROM</span> emp <span class="keyword">WHERE</span> deptid <span class="operator">=</span> <span class="number">4</span> <span class="keyword">AND</span> emp.age <span class="operator">=</span> <span class="number">30</span> <span class="keyword">AND</span> emp.`name` <span class="operator">=</span> <span class="string">&#x27;abcd&#x27;</span>;</span><br><span class="line">EXPLAIN <span class="keyword">SELECT</span> SQL_NO_CACHE <span class="operator">*</span> <span class="keyword">FROM</span> emp <span class="keyword">WHERE</span> emp.age <span class="operator">=</span> <span class="number">30</span> <span class="keyword">AND</span> emp.`name` <span class="operator">=</span> <span class="string">&#x27;abcd&#x27;</span>;</span><br><span class="line">EXPLAIN <span class="keyword">SELECT</span> SQL_NO_CACHE <span class="operator">*</span> <span class="keyword">FROM</span> emp <span class="keyword">WHERE</span> deptid <span class="operator">=</span> <span class="number">4</span> <span class="keyword">AND</span> emp.`name` <span class="operator">=</span> <span class="string">&#x27;abcd&#x27;</span>;</span><br></pre></td></tr></table></figure>

<p><strong>使用函数索引失效</strong></p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20201026210634.png" alt="image-20201026210633223"></p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20201026210650.png" alt="image-20201026210649062"></p>
<p>两个sql语句的作用是一样的。我们加上索引。<code>CREATE INDEX idx_name ON emp(name);</code></p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20201026210744.png" alt="image-20201026210743554"></p>
<p>此时第一条sql语句，索引优化已经生效啦</p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20201026211051.png" alt="image-20201026211049438"></p>
<p>而第二条sql语句依旧没有被优化，这是为什么呢？？</p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20201026211127.png" alt="image-20201026211125572"></p>
<p><strong>这是因为使用了函数导致索引优化失效！</strong></p>
<p><strong><mark>不在索引列上做任何操作（计算、函数、(自动or手动)类型转换），会导致索引失效而转向全表扫描！</mark></strong></p>
<p><strong>存储引擎不能使用索引中范围条件右边的列</strong></p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20201027135919.png" alt="image-20201027135910260"></p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20201027140002.png" alt="image-20201027140000653"></p>
<p>我们照样添加索引<code>CREATE INDEX idx_age_deptId_name ON emp(age,deptId,name);</code></p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20201027140127.png" alt="image-20201027140126014"></p>
<p>虽然查询时间大幅度减少了，但是还是没有先前使用复合索引那么快！这是为什么呢？？</p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20201027140228.png" alt="image-20201027140227619"></p>
<p>可以看出<code>key_len=10</code>命中的是<code>age</code>,<code>depId</code>。而<code>name</code>是失效的！</p>
<p><strong><mark>这就是存储引擎不能使用索引中范围条件右边的列<code>(age,deptId,name)</code>,<code>emp.deptId &gt; 20</code>导致<code>name</code>失效。</mark></strong></p>
<p><strong>所以我们要把使用范围条件的列在创建索引时放在最后面</strong>。<code>CREATE INDEX idx_age_name_deptId ON emp(age,name,deptId);</code></p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20201027140712.png" alt="image-20201027140710990"></p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20201027140751.png" alt="image-20201027140749751"></p>
<p>此时就全部使用上了。</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">## 存储引擎不能使用索引中范围条件右边的列</span><br><span class="line">EXPLAIN <span class="keyword">SELECT</span> SQL_NO_CACHE <span class="operator">*</span> <span class="keyword">FROM</span> emp <span class="keyword">WHERE</span> emp.age <span class="operator">=</span> <span class="number">30</span> <span class="keyword">AND</span> emp.deptId <span class="operator">&gt;</span> <span class="number">20</span> <span class="keyword">AND</span> emp.name <span class="operator">=</span> <span class="string">&#x27;abc&#x27;</span>;</span><br><span class="line"><span class="keyword">CREATE</span> INDEX idx_age_deptId_name <span class="keyword">ON</span> emp(age,deptId,name);</span><br><span class="line"></span><br><span class="line"><span class="keyword">CREATE</span> INDEX idx_age_name_deptId <span class="keyword">ON</span> emp(age,name,deptId);</span><br></pre></td></tr></table></figure>

<p><strong>mysql在使用不等于(!= 或者&lt;&gt;)的时候无法使用索引会导致全表扫描</strong></p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20201027141151.png" alt="image-20201027141150374"></p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20201027141208.png" alt="image-20201027141206979"></p>
<p>添加索引<code>CREATE INDEX idx_name ON emp(name);</code></p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20201027141302.png" alt="image-20201027141300403"></p>
<p>可以看到type依旧为all，并没有起到优化效果。</p>
<p><strong><mark>mysql在使用不等于(!= 或者&lt;&gt;)的时候无法使用索引会导致全表扫描</mark></strong></p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">## mysql 在使用不等于(<span class="operator">!=</span> 或者<span class="operator">&lt;&gt;</span>)的时候无法使用索引会导致全表扫描</span><br><span class="line">EXPLAIN <span class="keyword">SELECT</span> SQL_NO_CACHE <span class="operator">*</span> <span class="keyword">FROM</span> emp <span class="keyword">WHERE</span> emp.`name` <span class="operator">&lt;&gt;</span> <span class="string">&#x27;abc&#x27;</span>;</span><br><span class="line"><span class="keyword">CREATE</span> INDEX idx_name <span class="keyword">ON</span> emp(name);</span><br></pre></td></tr></table></figure>

<p><strong><code>is null</code>是可以使用索引的,<code>is not null</code>无法使用索引。</strong></p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20201027141741.png" alt="image-20201027141740024"></p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20201027141756.png" alt="image-20201027141755145"></p>
<p>添加索引<code>CREATE INDEX idx_age ON emp(age);</code></p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20201027141859.png" alt="image-20201027141852342"></p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20201027141921.png" alt="image-20201027141919814"></p>
<p><strong><mark><code>is null</code>是可以使用索引的,<code>is not null</code>无法使用索引。</mark></strong></p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">## `<span class="keyword">is</span> <span class="keyword">null</span>`是可以使用索引的,`<span class="keyword">is</span> <span class="keyword">not</span> <span class="keyword">null</span> `无法使用索引。</span><br><span class="line">EXPLAIN <span class="keyword">SELECT</span> SQL_NO_CACHE <span class="operator">*</span> <span class="keyword">FROM</span> emp <span class="keyword">WHERE</span> age <span class="keyword">IS</span> <span class="keyword">NULL</span>;</span><br><span class="line">EXPLAIN <span class="keyword">SELECT</span> SQL_NO_CACHE <span class="operator">*</span> <span class="keyword">FROM</span> emp <span class="keyword">WHERE</span> age <span class="keyword">IS</span> <span class="keyword">NOT</span> <span class="keyword">NULL</span>;</span><br><span class="line"><span class="keyword">CREATE</span> INDEX idx_age <span class="keyword">ON</span> emp(age);</span><br></pre></td></tr></table></figure>

<p><strong>like以通配符开头(‘%abc…’)mysql索引失效会变成全表扫描的操作</strong></p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20201027142144.png" alt=""></p>
<p>添加索引<code>CREATE INDEX idx_name ON emp(name);</code></p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20201027142308.png" alt="image-20201027142306879"></p>
<p><strong>可以看到依旧没有起到优化效果！这是因为导致查询条件不确定，必须要全部查找，所以导致失效。</strong></p>
<p><strong><mark>like以通配符开头(‘%abc…’)mysql索引失效会变成全表扫描的操作</mark></strong></p>
 <figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">## <span class="keyword">like</span>以通配符开头(<span class="string">&#x27;%abc...&#x27;</span>)mysql索引失效会变成全表扫描的操作</span><br><span class="line">EXPLAIN <span class="keyword">SELECT</span> SQL_NO_CACHE <span class="operator">*</span> <span class="keyword">FROM</span> emp <span class="keyword">WHERE</span> emp.`name` <span class="keyword">LIKE</span> <span class="string">&#x27;%abc%&#x27;</span>;</span><br><span class="line"><span class="keyword">CREATE</span> INDEX idx_name <span class="keyword">ON</span> emp(name);</span><br></pre></td></tr></table></figure>

<p><strong>字符串不加单引号索引失效</strong></p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20201027142736.png" alt="image-20201027142735291"></p>
<p>添加索引<code>CREATE INDEX idx_name ON emp(name);</code></p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20201027142816.png" alt="image-20201027142815606"></p>
<p><strong>依旧没有生效，这是因为<code>emp.</code>name<code>=123;</code>name为varchar类型，发生了类型自动转换而导致失效的。所以我们JavaBean对象要和数据库保存一致，防止出现类型自动转换。</strong></p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">## 字符串不加单引号索引失效</span><br><span class="line">EXPLAIN <span class="keyword">SELECT</span> SQL_NO_CACHE <span class="operator">*</span> <span class="keyword">FROM</span> emp <span class="keyword">WHERE</span> emp.`name`<span class="operator">=</span><span class="number">123</span>;</span><br><span class="line"><span class="keyword">CREATE</span> INDEX idx_name <span class="keyword">ON</span> emp(name);</span><br></pre></td></tr></table></figure>

<h3 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h3><ol>
<li>不在索引列上做任何操作（计算、函数、(自动or手动)类型转换），会导致索引失效而转向全表扫描。</li>
<li>存储引擎不能使用索引中范围条件右边的列</li>
<li>mysql 在使用不等于(!= 或者&lt;&gt;)的时候无法使用索引会导致全表扫描</li>
<li>is not null 也无法使用索引,但是is null是可以使用索引的</li>
<li>like以通配符开头(‘%abc…’)mysql索引失效会变成全表扫描的操作</li>
<li>字符串不加单引号索引失效（出现自动类型转换）</li>
</ol>
<p><strong>假设index(a,b,c)</strong></p>
<table>
<thead>
<tr>
<th>Where语句</th>
<th>索引是否被使用</th>
</tr>
</thead>
<tbody><tr>
<td>where a = 3</td>
<td>Y，使用到a</td>
</tr>
<tr>
<td>where a = 3 and b = 5</td>
<td>Y,使用到a，b</td>
</tr>
<tr>
<td>where a = 3 and b = 5 and c = 4</td>
<td>Y,使用到a,b,c</td>
</tr>
<tr>
<td>where b = 3 或者 where b = 3 and c = 4  或者  where c = 4</td>
<td>N</td>
</tr>
<tr>
<td>where a = 3 and c = 5</td>
<td>使用到a， 但是c不可以，b中间断了</td>
</tr>
<tr>
<td>where a = 3 and b &gt; 4 and c = 5</td>
<td>使用到a和b， c不能用在范围之后，b断了</td>
</tr>
<tr>
<td>where a is null and b is not null</td>
<td>is null 支持索引 但是is not null 不支持,所以 a 可以使用索引,但是 b不可以使用</td>
</tr>
<tr>
<td>where a &lt;&gt; 3</td>
<td>不能使用索引</td>
</tr>
<tr>
<td>where  abs(a) =3</td>
<td>不能使用 索引</td>
</tr>
<tr>
<td>where a = 3 and b like ‘kk%’ and c = 4</td>
<td>Y,使用到a,b,c</td>
</tr>
<tr>
<td>where a = 3 and b like ‘%kk’ and c = 4</td>
<td>Y,只用到a</td>
</tr>
<tr>
<td>where a = 3 and b like ‘%kk%’ and c = 4</td>
<td>Y,只用到a</td>
</tr>
<tr>
<td>where a = 3 and b like ‘k%kk%’ and c = 4</td>
<td>Y,使用到a,b,c</td>
</tr>
</tbody></table>
<p>建议（query过滤性就是类似身份证号这些唯一的，能够快速过滤其他的性质）</p>
<ol>
<li>对于单键索引，尽量选择针对当前query过滤性更好的索引</li>
<li>在选择组合索引的时候，当前Query中过滤性最好的字段在索引字段顺序中，位置越靠前越好。</li>
<li>在选择组合索引的时候，尽量选择可以能够包含当前query中的where字句中更多字段的索引</li>
<li>在选择组合索引的时候，如果某个字段可能出现范围查询时，尽量把这个字段放在索引次序的最后面</li>
<li>书写sql语句时，尽量避免造成索引失效的情况</li>
</ol>
<h2 id="关联查询"><a href="#关联查询" class="headerlink" title="关联查询"></a>关联查询</h2><figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">CREATE</span> <span class="keyword">TABLE</span> IF <span class="keyword">NOT</span> <span class="keyword">EXISTS</span> `class` (</span><br><span class="line">`id` <span class="type">INT</span>(<span class="number">10</span>) UNSIGNED <span class="keyword">NOT</span> <span class="keyword">NULL</span> AUTO_INCREMENT,</span><br><span class="line">`card` <span class="type">INT</span>(<span class="number">10</span>) UNSIGNED <span class="keyword">NOT</span> <span class="keyword">NULL</span>,</span><br><span class="line"><span class="keyword">PRIMARY</span> KEY (`id`)</span><br><span class="line">);</span><br><span class="line"><span class="keyword">CREATE</span> <span class="keyword">TABLE</span> IF <span class="keyword">NOT</span> <span class="keyword">EXISTS</span> `book` (</span><br><span class="line">`bookid` <span class="type">INT</span>(<span class="number">10</span>) UNSIGNED <span class="keyword">NOT</span> <span class="keyword">NULL</span> AUTO_INCREMENT,</span><br><span class="line">`card` <span class="type">INT</span>(<span class="number">10</span>) UNSIGNED <span class="keyword">NOT</span> <span class="keyword">NULL</span>,</span><br><span class="line"><span class="keyword">PRIMARY</span> KEY (`bookid`)</span><br><span class="line">);</span><br><span class="line"></span><br><span class="line"><span class="keyword">INSERT</span> <span class="keyword">INTO</span> class(card) <span class="keyword">VALUES</span>(<span class="built_in">FLOOR</span>(<span class="number">1</span> <span class="operator">+</span> (RAND() <span class="operator">*</span> <span class="number">20</span>)));</span><br><span class="line"><span class="keyword">INSERT</span> <span class="keyword">INTO</span> class(card) <span class="keyword">VALUES</span>(<span class="built_in">FLOOR</span>(<span class="number">1</span> <span class="operator">+</span> (RAND() <span class="operator">*</span> <span class="number">20</span>)));</span><br><span class="line"><span class="keyword">INSERT</span> <span class="keyword">INTO</span> class(card) <span class="keyword">VALUES</span>(<span class="built_in">FLOOR</span>(<span class="number">1</span> <span class="operator">+</span> (RAND() <span class="operator">*</span> <span class="number">20</span>)));</span><br><span class="line"><span class="keyword">INSERT</span> <span class="keyword">INTO</span> class(card) <span class="keyword">VALUES</span>(<span class="built_in">FLOOR</span>(<span class="number">1</span> <span class="operator">+</span> (RAND() <span class="operator">*</span> <span class="number">20</span>)));</span><br><span class="line"><span class="keyword">INSERT</span> <span class="keyword">INTO</span> class(card) <span class="keyword">VALUES</span>(<span class="built_in">FLOOR</span>(<span class="number">1</span> <span class="operator">+</span> (RAND() <span class="operator">*</span> <span class="number">20</span>)));</span><br><span class="line"><span class="keyword">INSERT</span> <span class="keyword">INTO</span> class(card) <span class="keyword">VALUES</span>(<span class="built_in">FLOOR</span>(<span class="number">1</span> <span class="operator">+</span> (RAND() <span class="operator">*</span> <span class="number">20</span>)));</span><br><span class="line"><span class="keyword">INSERT</span> <span class="keyword">INTO</span> class(card) <span class="keyword">VALUES</span>(<span class="built_in">FLOOR</span>(<span class="number">1</span> <span class="operator">+</span> (RAND() <span class="operator">*</span> <span class="number">20</span>)));</span><br><span class="line"><span class="keyword">INSERT</span> <span class="keyword">INTO</span> class(card) <span class="keyword">VALUES</span>(<span class="built_in">FLOOR</span>(<span class="number">1</span> <span class="operator">+</span> (RAND() <span class="operator">*</span> <span class="number">20</span>)));</span><br><span class="line"><span class="keyword">INSERT</span> <span class="keyword">INTO</span> class(card) <span class="keyword">VALUES</span>(<span class="built_in">FLOOR</span>(<span class="number">1</span> <span class="operator">+</span> (RAND() <span class="operator">*</span> <span class="number">20</span>)));</span><br><span class="line"><span class="keyword">INSERT</span> <span class="keyword">INTO</span> class(card) <span class="keyword">VALUES</span>(<span class="built_in">FLOOR</span>(<span class="number">1</span> <span class="operator">+</span> (RAND() <span class="operator">*</span> <span class="number">20</span>)));</span><br><span class="line"><span class="keyword">INSERT</span> <span class="keyword">INTO</span> class(card) <span class="keyword">VALUES</span>(<span class="built_in">FLOOR</span>(<span class="number">1</span> <span class="operator">+</span> (RAND() <span class="operator">*</span> <span class="number">20</span>)));</span><br><span class="line"><span class="keyword">INSERT</span> <span class="keyword">INTO</span> class(card) <span class="keyword">VALUES</span>(<span class="built_in">FLOOR</span>(<span class="number">1</span> <span class="operator">+</span> (RAND() <span class="operator">*</span> <span class="number">20</span>)));</span><br><span class="line"><span class="keyword">INSERT</span> <span class="keyword">INTO</span> class(card) <span class="keyword">VALUES</span>(<span class="built_in">FLOOR</span>(<span class="number">1</span> <span class="operator">+</span> (RAND() <span class="operator">*</span> <span class="number">20</span>)));</span><br><span class="line"><span class="keyword">INSERT</span> <span class="keyword">INTO</span> class(card) <span class="keyword">VALUES</span>(<span class="built_in">FLOOR</span>(<span class="number">1</span> <span class="operator">+</span> (RAND() <span class="operator">*</span> <span class="number">20</span>)));</span><br><span class="line"><span class="keyword">INSERT</span> <span class="keyword">INTO</span> class(card) <span class="keyword">VALUES</span>(<span class="built_in">FLOOR</span>(<span class="number">1</span> <span class="operator">+</span> (RAND() <span class="operator">*</span> <span class="number">20</span>)));</span><br><span class="line"><span class="keyword">INSERT</span> <span class="keyword">INTO</span> class(card) <span class="keyword">VALUES</span>(<span class="built_in">FLOOR</span>(<span class="number">1</span> <span class="operator">+</span> (RAND() <span class="operator">*</span> <span class="number">20</span>)));</span><br><span class="line"><span class="keyword">INSERT</span> <span class="keyword">INTO</span> class(card) <span class="keyword">VALUES</span>(<span class="built_in">FLOOR</span>(<span class="number">1</span> <span class="operator">+</span> (RAND() <span class="operator">*</span> <span class="number">20</span>)));</span><br><span class="line"><span class="keyword">INSERT</span> <span class="keyword">INTO</span> class(card) <span class="keyword">VALUES</span>(<span class="built_in">FLOOR</span>(<span class="number">1</span> <span class="operator">+</span> (RAND() <span class="operator">*</span> <span class="number">20</span>)));</span><br><span class="line"><span class="keyword">INSERT</span> <span class="keyword">INTO</span> class(card) <span class="keyword">VALUES</span>(<span class="built_in">FLOOR</span>(<span class="number">1</span> <span class="operator">+</span> (RAND() <span class="operator">*</span> <span class="number">20</span>)));</span><br><span class="line"><span class="keyword">INSERT</span> <span class="keyword">INTO</span> class(card) <span class="keyword">VALUES</span>(<span class="built_in">FLOOR</span>(<span class="number">1</span> <span class="operator">+</span> (RAND() <span class="operator">*</span> <span class="number">20</span>)));</span><br><span class="line"></span><br><span class="line"><span class="keyword">INSERT</span> <span class="keyword">INTO</span> book(card) <span class="keyword">VALUES</span>(<span class="built_in">FLOOR</span>(<span class="number">1</span> <span class="operator">+</span> (RAND() <span class="operator">*</span> <span class="number">20</span>)));</span><br><span class="line"><span class="keyword">INSERT</span> <span class="keyword">INTO</span> book(card) <span class="keyword">VALUES</span>(<span class="built_in">FLOOR</span>(<span class="number">1</span> <span class="operator">+</span> (RAND() <span class="operator">*</span> <span class="number">20</span>)));</span><br><span class="line"><span class="keyword">INSERT</span> <span class="keyword">INTO</span> book(card) <span class="keyword">VALUES</span>(<span class="built_in">FLOOR</span>(<span class="number">1</span> <span class="operator">+</span> (RAND() <span class="operator">*</span> <span class="number">20</span>)));</span><br><span class="line"><span class="keyword">INSERT</span> <span class="keyword">INTO</span> book(card) <span class="keyword">VALUES</span>(<span class="built_in">FLOOR</span>(<span class="number">1</span> <span class="operator">+</span> (RAND() <span class="operator">*</span> <span class="number">20</span>)));</span><br><span class="line"><span class="keyword">INSERT</span> <span class="keyword">INTO</span> book(card) <span class="keyword">VALUES</span>(<span class="built_in">FLOOR</span>(<span class="number">1</span> <span class="operator">+</span> (RAND() <span class="operator">*</span> <span class="number">20</span>)));</span><br><span class="line"><span class="keyword">INSERT</span> <span class="keyword">INTO</span> book(card) <span class="keyword">VALUES</span>(<span class="built_in">FLOOR</span>(<span class="number">1</span> <span class="operator">+</span> (RAND() <span class="operator">*</span> <span class="number">20</span>)));</span><br><span class="line"><span class="keyword">INSERT</span> <span class="keyword">INTO</span> book(card) <span class="keyword">VALUES</span>(<span class="built_in">FLOOR</span>(<span class="number">1</span> <span class="operator">+</span> (RAND() <span class="operator">*</span> <span class="number">20</span>)));</span><br><span class="line"><span class="keyword">INSERT</span> <span class="keyword">INTO</span> book(card) <span class="keyword">VALUES</span>(<span class="built_in">FLOOR</span>(<span class="number">1</span> <span class="operator">+</span> (RAND() <span class="operator">*</span> <span class="number">20</span>)));</span><br><span class="line"><span class="keyword">INSERT</span> <span class="keyword">INTO</span> book(card) <span class="keyword">VALUES</span>(<span class="built_in">FLOOR</span>(<span class="number">1</span> <span class="operator">+</span> (RAND() <span class="operator">*</span> <span class="number">20</span>)));</span><br><span class="line"><span class="keyword">INSERT</span> <span class="keyword">INTO</span> book(card) <span class="keyword">VALUES</span>(<span class="built_in">FLOOR</span>(<span class="number">1</span> <span class="operator">+</span> (RAND() <span class="operator">*</span> <span class="number">20</span>)));</span><br><span class="line"><span class="keyword">INSERT</span> <span class="keyword">INTO</span> book(card) <span class="keyword">VALUES</span>(<span class="built_in">FLOOR</span>(<span class="number">1</span> <span class="operator">+</span> (RAND() <span class="operator">*</span> <span class="number">20</span>)));</span><br><span class="line"><span class="keyword">INSERT</span> <span class="keyword">INTO</span> book(card) <span class="keyword">VALUES</span>(<span class="built_in">FLOOR</span>(<span class="number">1</span> <span class="operator">+</span> (RAND() <span class="operator">*</span> <span class="number">20</span>)));</span><br><span class="line"><span class="keyword">INSERT</span> <span class="keyword">INTO</span> book(card) <span class="keyword">VALUES</span>(<span class="built_in">FLOOR</span>(<span class="number">1</span> <span class="operator">+</span> (RAND() <span class="operator">*</span> <span class="number">20</span>)));</span><br><span class="line"><span class="keyword">INSERT</span> <span class="keyword">INTO</span> book(card) <span class="keyword">VALUES</span>(<span class="built_in">FLOOR</span>(<span class="number">1</span> <span class="operator">+</span> (RAND() <span class="operator">*</span> <span class="number">20</span>)));</span><br><span class="line"><span class="keyword">INSERT</span> <span class="keyword">INTO</span> book(card) <span class="keyword">VALUES</span>(<span class="built_in">FLOOR</span>(<span class="number">1</span> <span class="operator">+</span> (RAND() <span class="operator">*</span> <span class="number">20</span>)));</span><br><span class="line"><span class="keyword">INSERT</span> <span class="keyword">INTO</span> book(card) <span class="keyword">VALUES</span>(<span class="built_in">FLOOR</span>(<span class="number">1</span> <span class="operator">+</span> (RAND() <span class="operator">*</span> <span class="number">20</span>)));</span><br><span class="line"><span class="keyword">INSERT</span> <span class="keyword">INTO</span> book(card) <span class="keyword">VALUES</span>(<span class="built_in">FLOOR</span>(<span class="number">1</span> <span class="operator">+</span> (RAND() <span class="operator">*</span> <span class="number">20</span>)));</span><br><span class="line"><span class="keyword">INSERT</span> <span class="keyword">INTO</span> book(card) <span class="keyword">VALUES</span>(<span class="built_in">FLOOR</span>(<span class="number">1</span> <span class="operator">+</span> (RAND() <span class="operator">*</span> <span class="number">20</span>)));</span><br><span class="line"><span class="keyword">INSERT</span> <span class="keyword">INTO</span> book(card) <span class="keyword">VALUES</span>(<span class="built_in">FLOOR</span>(<span class="number">1</span> <span class="operator">+</span> (RAND() <span class="operator">*</span> <span class="number">20</span>)));</span><br><span class="line"><span class="keyword">INSERT</span> <span class="keyword">INTO</span> book(card) <span class="keyword">VALUES</span>(<span class="built_in">FLOOR</span>(<span class="number">1</span> <span class="operator">+</span> (RAND() <span class="operator">*</span> <span class="number">20</span>)));</span><br></pre></td></tr></table></figure>

<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20201027151046.png" alt="image-20201027151044101"></p>
<p>首先给book表建立索引<code>ALTER TABLE</code>book<code>ADD INDEX Y (</code>card<code>);</code></p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20201027151126.png" alt="image-20201027151124361"></p>
<p>索引优化生效，再给class表建立索引<code>ALTER TABLE</code>class<code>ADD INDEX Y (</code>card<code>);</code></p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20201027151230.png" alt="image-20201027151228196"></p>
<p>虽然索引建立成功了，但是还是没有达到对class对优化效果。</p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20201027151415.png" alt="image-20201027151413449"></p>
<p><strong>这是因为此时的<code>class</code>表是驱动表，<code>book</code>表是被驱动表，给驱动表建立索引是避免不了全表扫描的。所以我们只能给被驱动表建立索引优化。</strong></p>
<p>我们改成使用<code>inner Join</code>连接两表查询。</p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20201027151756.png" alt="image-20201027151746222"></p>
<p>id相同，按照由上至下的顺序执行，所以<code>book</code> 变成了驱动表，<code>class</code> 表变成了被驱动表。class的索引优化生效。</p>
<ol>
<li>保证被驱动表的join字段已经被索引</li>
<li>left join 时，选择小表作为驱动表，大表作为被驱动表。</li>
<li>inner join 时，mysql会自己帮你把小结果集的表选为驱动表。</li>
<li>虚拟表无法建立索引</li>
<li>子查询尽量不要放在被驱动表，有可能使用不到索引。</li>
<li>能够直接多表关联的尽量直接关联，不用子查询。</li>
</ol>
<h2 id="子查询优化"><a href="#子查询优化" class="headerlink" title="子查询优化"></a>子查询优化</h2><figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">SELECT</span> <span class="operator">*</span> <span class="keyword">FROM</span> t_emp a <span class="keyword">WHERE</span> a.id <span class="keyword">NOT</span> <span class="keyword">IN</span></span><br><span class="line">(<span class="keyword">SELECT</span> b.ceo <span class="keyword">FROM</span> t_dept b <span class="keyword">where</span> b.ceo <span class="keyword">IS</span> <span class="keyword">NO</span> <span class="keyword">NULL</span>);</span><br><span class="line"></span><br><span class="line"><span class="keyword">SELECT</span> <span class="operator">*</span> <span class="keyword">FROM</span> t_emp a <span class="keyword">LEFT</span> <span class="keyword">JOIN</span> t_dept b <span class="keyword">ON</span> a.id <span class="operator">=</span> b.ceo </span><br><span class="line"><span class="keyword">WHERE</span> b.id <span class="keyword">IS</span> <span class="keyword">NULL</span>;</span><br></pre></td></tr></table></figure>



<p>尽量不要使用<code>not in</code>或者<code>not exists</code>用<code>left outer join on xxx is null</code>替代</p>
<h2 id="排序分组优化"><a href="#排序分组优化" class="headerlink" title="排序分组优化"></a>排序分组优化</h2><h3 id="order-by"><a href="#order-by" class="headerlink" title="order by"></a>order by</h3><p><strong>无过滤 不索引</strong> </p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20201027160228.png" alt="image-20201027160226496"></p>
<p>我们加上<code>CREATE INDEX idx_age_deptId_name on emp(age,deptId,</code>name<code>);</code></p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20201027160303.png" alt="image-20201027160302656"></p>
<p>还是无法进行优化，此时我们在后面加上<code>limit</code>进行过滤</p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20201027160417.png" alt="image-20201027160415692"></p>
<p>发现此时的优化效果已经出来了。</p>
<p>所以我们使用order by语句时要对其进行过滤。</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">#无过滤 不索引 </span><br><span class="line">EXPLAIN <span class="keyword">SELECT</span> SQL_NO_CACHE <span class="operator">*</span> <span class="keyword">FROM</span> emp <span class="keyword">ORDER</span> <span class="keyword">BY</span> age,deptId;</span><br><span class="line"></span><br><span class="line">EXPLAIN <span class="keyword">SELECT</span> SQL_NO_CACHE <span class="operator">*</span> <span class="keyword">FROM</span> emp <span class="keyword">ORDER</span> <span class="keyword">BY</span> age,deptId LIMIT <span class="number">10</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">CREATE</span> INDEX idx_age_deptId_name <span class="keyword">on</span> emp(age,deptId,`name`);</span><br></pre></td></tr></table></figure>

<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20201027162324.png" alt="image-20201027162322718"></p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">CREATE</span> INDEX idx_age_deptId_name <span class="keyword">on</span> emp(age,deptId,`name`);</span><br><span class="line"></span><br><span class="line">EXPLAIN <span class="keyword">SELECT</span> <span class="operator">*</span> <span class="keyword">FROM</span> emp <span class="keyword">WHERE</span> age <span class="operator">=</span> <span class="number">45</span> <span class="keyword">ORDER</span> <span class="keyword">BY</span> deptId;##用上索引</span><br><span class="line"></span><br><span class="line">EXPLAIN <span class="keyword">SELECT</span> <span class="operator">*</span> <span class="keyword">FROM</span> emp <span class="keyword">WHERE</span> age <span class="operator">=</span> <span class="number">45</span> <span class="keyword">ORDER</span> <span class="keyword">BY</span> deptId,`name`;##用上索引</span><br><span class="line"></span><br><span class="line">EXPLAIN <span class="keyword">SELECT</span> <span class="operator">*</span> <span class="keyword">FROM</span> emp <span class="keyword">WHERE</span> age <span class="operator">=</span> <span class="number">45</span> <span class="keyword">ORDER</span> <span class="keyword">BY</span> deptId,empno;## empno没有索引  <span class="keyword">Using</span> filesort</span><br><span class="line"></span><br><span class="line">EXPLAIN <span class="keyword">SELECT</span> <span class="operator">*</span> <span class="keyword">FROM</span> emp <span class="keyword">WHERE</span> age <span class="operator">=</span> <span class="number">45</span> <span class="keyword">ORDER</span> <span class="keyword">BY</span> `name`,deptId;##索引顺序错 <span class="keyword">Using</span> filesort</span><br><span class="line"></span><br><span class="line">EXPLAIN <span class="keyword">SELECT</span> <span class="operator">*</span> <span class="keyword">FROM</span> emp <span class="keyword">WHERE</span> deptId <span class="operator">=</span> <span class="number">45</span> <span class="keyword">ORDER</span> <span class="keyword">BY</span> age;##索引顺序错 <span class="keyword">Using</span> filesort</span><br></pre></td></tr></table></figure>

<p><strong>where条件进行过滤，索引顺序要保证，不能错，不能断。</strong></p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20201027162602.png" alt="image-20201027162559466"></p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20201027162626.png" alt="image-20201027162624823"></p>
<p><strong>排序顺序要保持一致，不能一升一反。</strong></p>
<h3 id="索引选择"><a href="#索引选择" class="headerlink" title="索引选择"></a>索引选择</h3><p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20201027164913.png" alt="image-20201027164910892"></p>
<p>我们首先创建<code>CREATE INDEX idx_age_empno_name on emp(age,empno,</code>name<code>);</code>创建这个索引由于<code>empno</code>采用了范围查询，所以导致<code>name</code>失效</p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20201027165117.png" alt="image-20201027165115673"></p>
<p>删除索引，再次创建<code>CREATE INDEX idx_age_name on emp(age,</code>name<code>);</code></p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20201027165213.png" alt="image-20201027165212353"></p>
<p>消除了<code>Using filesort</code>，再把刚才删除的索引给创建。运行查看mysql选择使用那个索引</p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20201027165335.png" alt="image-20201027165334141"></p>
<p>可以看见mysql选择了<code>idx_age_empno_name</code>索引，虽然导致了<code>Using filesort</code>，但是rows却少了很多！！从而查询效率更高！</p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20201027165538.png" alt="image-20201027165530696"></p>
<p>因为<code>empno &lt; 101000</code>这个条件使用了索引，大幅度减少了扫描数量。从而mysql选择了这个索引！！</p>
<p><strong><mark>结论：  当范围条件和group by 或者 order by 的字段出现二选一时 ， 优先观察条件字段的过滤数量 ，如果过滤的数据足够多，而需要排序的数据并不多时，优先把索引放在范围字段上。反之，亦然。同时要相信mysql选择索引的能力！</mark></strong></p>
<h3 id="Using-filesort"><a href="#Using-filesort" class="headerlink" title="Using filesort"></a>Using filesort</h3><p>当我们没有办法避免<code>Using filesort</code>时，filesort有两种算法：mysql就要启动双路排序和单路排序。</p>
<p><strong>双路排序：MySQL 4.1之前是使用双路排序,字面意思就是两次扫描磁盘，最终得到数据，读取行指针和orderby列，对他们进行排序，然后扫描已经排序好的列表，按照列表中的值重新从列表中读取对应的数据输出。从磁盘取排序字段，在buffer进行排序，再从磁盘取其他字段。</strong></p>
<p>取一批数据，要对磁盘进行了两次扫描，众所周知，I\O是很耗时的，所以在mysql4.1之后，出现了第二种改进的算法，就是单路排序。</p>
<p><strong>单路排序：从磁盘读取查询需要的所有列，按照order by列在buffer对它们进行排序，然后扫描排序后的列表进行输出，它的效率更快一些，避免了第二次读取数据。并且把随机IO变成了顺序IO,但是它会使用更多的空间，因为它把每一行都保存在内存中了。</strong></p>
<p>由于单路是后出的，总体而言好过双路。但是用单路有问题</p>
<p>在sort_buffer中，方法B比方法A要多占用很多空间，因为方法B是把所有字段都取出, 所以有可能取出的数据的总大小超出了sort_buffer的容量，导致每次只能取sort_buffer容量大小的数据，进行排序（创建tmp文件，多路合并），排完再取取sort_buffer容量大小，再排……从而多次I/O。 </p>
<p>本来想省一次I/O操作，反而导致了大量的I/O操作，反而得不偿失。 </p>
<p>优化策略</p>
<ul>
<li>增大sort_buffer_size参数的设置</li>
<li>增大max_length_for_sort_data参数的设置</li>
<li>减少select 后面的查询的字段。</li>
</ul>
<p>提高Order By的速度 </p>
<ol>
<li><p>Order by时select * 是一个大忌只Query需要的字段， 这点非常重要。在这里的影响是： </p>
<ul>
<li><p>当Query的字段大小总和小于max_length_for_sort_data 而且排序字段不是 TEXT|BLOB 类型时，会用改进后的算法——单路排序， 否则用老算法——多路排序。 </p>
</li>
<li><p>两种算法的数据都有可能超出sort_buffer的容量，超出之后，会创建tmp文件进行合并排序，导致多次I/O，但是用单路排序算法的风险会更大一些,所以要提高sort_buffer_size。</p>
</li>
</ul>
<ol start="2">
<li>尝试提高 sort_buffer_size 不管用哪种算法，提高这个参数都会提高效率，当然，要根据系统的能力去提高，因为这个参数是针对每个进程的 <strong>1M-8M之间调整</strong></li>
<li>尝试提高 max_length_for_sort_data 提高这个参数， 会增加用改进算法的概率。但是如果设的太高，数据总容量超出sort_buffer_size的概率就增大，明显症状是高的磁盘I/O活动和低的处理器使用率.  <strong>1024-8192之间调整</strong></li>
</ol>
</li>
</ol>
<h3 id="group-by"><a href="#group-by" class="headerlink" title="group by"></a>group by</h3><p><strong>group by 使用索引的原则几乎跟order by一致 ，唯一区别是groupby 即使没有过滤条件用到索引，也可以直接使用索引。</strong></p>
<h2 id="覆盖索引"><a href="#覆盖索引" class="headerlink" title="覆盖索引"></a>覆盖索引</h2><p>什么是覆盖索引？ 简单说就是，select 到 from 之间查询的列 &lt;=使用的索引列+主键 </p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20201027171239.png" alt="image-20201027171236242"></p>
<p><code>explain select * from emp where name like &#39;%abc&#39;;</code></p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20201027171327.png" alt="image-20201027171313348"></p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20201027171406.png" alt="image-20201027171404868"></p>
<p>使用覆盖索引后 </p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20201027171428.png" alt="image-20201027171425615"></p>
<p>也就是不要使用<code>select *</code></p>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">Kylin</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://www.codekylin.cn/24797.html">https://www.codekylin.cn/24797.html</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://www.codekylin.cn" target="_blank">Kylin</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/%E6%95%B0%E6%8D%AE%E5%BA%93/">数据库</a><a class="post-meta__tags" href="/tags/MySQL/">MySQL</a></div><div class="post_share"><div class="social-share" data-image="https://qiniu.codekylin.cn/github/img/img/code1.jpg" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/social-share.js/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/social-share.js/dist/js/social-share.min.js" defer></script></div></div><div class="post-reward"><div class="reward-button button--animated"><i class="fas fa-qrcode"></i> 打赏</div><div class="reward-main"><ul class="reward-all"><li class="reward-item"><a href="https://qiniu.codekylin.cn/img/20200807181442.jpg" target="_blank"><img class="post-qr-code-img" data-lazy-src="https://qiniu.codekylin.cn/img/20200807181442.jpg" alt="微信"/></a><div class="post-qr-code-desc">微信</div></li><li class="reward-item"><a href="https://qiniu.codekylin.cn/img/20200807181505.jpg" target="_blank"><img class="post-qr-code-img" data-lazy-src="https://qiniu.codekylin.cn/img/20200807181505.jpg" alt="支付寶"/></a><div class="post-qr-code-desc">支付寶</div></li></ul></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/40460.html"><img class="prev-cover" data-lazy-src="https://qiniu.codekylin.cn/github/img/img/deepin-2.png" onerror="onerror=null;src='/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">MySQL之查询截取分析</div></div></a></div><div class="next-post pull-right"><a href="/15002.html"><img class="next-cover" data-lazy-src="https://qiniu.codekylin.cn/github/img/img/deepin-1.png" onerror="onerror=null;src='/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">MySQL之Explain性能分析</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span> 相关推荐</span></div><div class="relatedPosts-list"><div><a href="/16118.html" title="MySQL主从复制"><img class="cover" data-lazy-src="https://qiniu.codekylin.cn/github/img/img/wallhaven-3kp6yv.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-10-29</div><div class="title">MySQL主从复制</div></div></a></div><div><a href="/14571.html" title="MySQL存储引擎"><img class="cover" data-lazy-src="https://qiniu.codekylin.cn/github/img/img/博客封面18.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-10-25</div><div class="title">MySQL存储引擎</div></div></a></div><div><a href="/15002.html" title="MySQL之Explain性能分析"><img class="cover" data-lazy-src="https://qiniu.codekylin.cn/github/img/img/deepin-1.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-10-25</div><div class="title">MySQL之Explain性能分析</div></div></a></div><div><a href="/40460.html" title="MySQL之查询截取分析"><img class="cover" data-lazy-src="https://qiniu.codekylin.cn/github/img/img/deepin-2.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-10-27</div><div class="title">MySQL之查询截取分析</div></div></a></div><div><a href="/34856.html" title="MySQL数据库-1"><img class="cover" data-lazy-src="https://qiniu.codekylin.cn/github/images/20200718200005.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2019-09-28</div><div class="title">MySQL数据库-1</div></div></a></div><div><a href="/33592.html" title="MySQL索引"><img class="cover" data-lazy-src="https://qiniu.codekylin.cn/github/img/img/荒鲸.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-10-25</div><div class="title">MySQL索引</div></div></a></div></div></div><hr/><div id="post-comment"><div class="comment-head"><div class="comment-headline"><i class="fas fa-comments fa-fw"></i><span> 评论</span></div></div><div class="comment-wrap"><div><div class="vcomment" id="vcomment"></div></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="card-info-avatar is-center"><img class="avatar-img" data-lazy-src="https://qiniu.codekylin.cn/img/20200807181526.jpg" onerror="this.onerror=null;this.src='https://qiniu.codekylin.cn/github/img/friend_404.gif'" alt="avatar"/><div class="author-info__name">Kylin</div><div class="author-info__description">学习不易，努力努力~</div></div><div class="card-info-data"><div class="card-info-data-item is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">362</div></a></div><div class="card-info-data-item is-center"><a href="/tags/"><div class="headline">标签</div><div class="length-num">427</div></a></div><div class="card-info-data-item is-center"><a href="/categories/"><div class="headline">分类</div><div class="length-num">101</div></a></div></div><a class="button--animated" id="card-info-btn"><i class="fas fa-bookmark"></i><span>加入书签</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://github.com/kylincw" target="_blank" title="Github"><i class="iconfont icon-github"></i></a><a class="social-icon" href="tencent://message/?Menu=yes&amp;uin=171346168&amp;Service=300&amp;sigT=45a1e5847943b64c6ff3990f8a9e644d2b31356cb0b4ac6b24663a3c8dd0f8aa12a595b1714f9d45" target="_blank" title="qq"><i class="iconfont icon-qq"></i></a><a class="social-icon" href="https://space.bilibili.com/53836035" target="_blank" title="BiliBili"><i class="iconfont icon-bilibili-line"></i></a><a class="social-icon" href="mailto:zhang171346168@qq.com" target="_blank" title="Email"><i class="iconfont icon-email1"></i></a><a class="social-icon" href="/atom.xml" target="_blank" title="RSS"><i class="iconfont icon-rss"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn card-announcement-animation"></i><span>公告</span></div><div class="announcement_content">学习不易，努力努力！</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%8E%AF%E5%A2%83%E6%90%AD%E5%BB%BA"><span class="toc-number">1.</span> <span class="toc-text">环境搭建</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%BB%BA%E8%A1%A8%E8%AF%AD%E5%8F%A5"><span class="toc-number">1.1.</span> <span class="toc-text">建表语句</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%88%9B%E5%BB%BA%E5%87%BD%E6%95%B0"><span class="toc-number">1.2.</span> <span class="toc-text">创建函数</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%88%9B%E5%BB%BA%E8%B0%83%E7%94%A8%E5%AD%98%E5%82%A8%E8%BF%87%E7%A8%8B"><span class="toc-number">1.3.</span> <span class="toc-text">创建调用存储过程</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%88%A0%E9%99%A4%E7%B4%A2%E5%BC%95"><span class="toc-number">1.4.</span> <span class="toc-text">删除索引</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%8D%95%E8%A1%A8%E4%BD%BF%E7%94%A8%E7%B4%A2%E5%BC%95%E5%8F%8A%E5%B8%B8%E8%A7%81%E7%B4%A2%E5%BC%95%E5%A4%B1%E6%95%88"><span class="toc-number">2.</span> <span class="toc-text">单表使用索引及常见索引失效</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%A1%88%E4%BE%8B"><span class="toc-number">2.1.</span> <span class="toc-text">案例</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%80%BB%E7%BB%93"><span class="toc-number">2.2.</span> <span class="toc-text">总结</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%85%B3%E8%81%94%E6%9F%A5%E8%AF%A2"><span class="toc-number">3.</span> <span class="toc-text">关联查询</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%AD%90%E6%9F%A5%E8%AF%A2%E4%BC%98%E5%8C%96"><span class="toc-number">4.</span> <span class="toc-text">子查询优化</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%8E%92%E5%BA%8F%E5%88%86%E7%BB%84%E4%BC%98%E5%8C%96"><span class="toc-number">5.</span> <span class="toc-text">排序分组优化</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#order-by"><span class="toc-number">5.1.</span> <span class="toc-text">order by</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%B4%A2%E5%BC%95%E9%80%89%E6%8B%A9"><span class="toc-number">5.2.</span> <span class="toc-text">索引选择</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Using-filesort"><span class="toc-number">5.3.</span> <span class="toc-text">Using filesort</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#group-by"><span class="toc-number">5.4.</span> <span class="toc-text">group by</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E8%A6%86%E7%9B%96%E7%B4%A2%E5%BC%95"><span class="toc-number">6.</span> <span class="toc-text">覆盖索引</span></a></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/56352.html" title="be动词"><img data-lazy-src="https://qiniu.codekylin.cn/github/img/img/博客封面10.png" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="be动词"/></a><div class="content"><a class="title" href="/56352.html" title="be动词">be动词</a><time datetime="2022-07-12T11:47:29.800Z" title="更新于 2022-07-12 19:47:29">2022-07-12</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/36436.html" title="JVM堆内存"><img data-lazy-src="https://qiniu.codekylin.cn/img/20200418115059.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="JVM堆内存"/></a><div class="content"><a class="title" href="/36436.html" title="JVM堆内存">JVM堆内存</a><time datetime="2022-07-12T11:47:29.800Z" title="更新于 2022-07-12 19:47:29">2022-07-12</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/44292.html" title="Java多线程详解"><img data-lazy-src="https://qiniu.codekylin.cn/github/img/img/wallhaven-eorjzk.png" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Java多线程详解"/></a><div class="content"><a class="title" href="/44292.html" title="Java多线程详解">Java多线程详解</a><time datetime="2022-07-12T11:47:29.800Z" title="更新于 2022-07-12 19:47:29">2022-07-12</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/40200.html" title="谷粒商城记录"><img data-lazy-src="https://qiniu.codekylin.cn/github/img/img/wallhaven-6qvvrx.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="谷粒商城记录"/></a><div class="content"><a class="title" href="/40200.html" title="谷粒商城记录">谷粒商城记录</a><time datetime="2022-07-12T11:47:29.800Z" title="更新于 2022-07-12 19:47:29">2022-07-12</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/27082.html" title="Spring学习-3"><img data-lazy-src="https://qiniu.codekylin.cn/github/img/img/wallhaven-4x28xo.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Spring学习-3"/></a><div class="content"><a class="title" href="/27082.html" title="Spring学习-3">Spring学习-3</a><time datetime="2022-07-12T11:47:29.799Z" title="更新于 2022-07-12 19:47:29">2022-07-12</time></div></div></div></div></div></div></main><footer id="footer" style="background-image: url('https://qiniu.codekylin.cn/github/img/img/code1.jpg')"><div id="footer-wrap"><div class="copyright">&copy;2019 - 2022 By Kylin</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div><div class="footer_custom_text"><a target="_blank" rel="noopener" href="https://beian.miit.gov.cn/"><img class="icp-icon" src="https://img.alicdn.com/tfs/TB1..50QpXXXXX7XpXXXXXXXXXX-40-40.png"><span>湘ICP备2022005420号-1</span></a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="font-plus" type="button" title="放大字体"><i class="fas fa-plus"></i></button><button id="font-minus" type="button" title="缩小字体"><i class="fas fa-minus"></i></button><button id="translateLink" type="button" title="简繁转换">繁</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><a id="to_comment" href="#post-comment" title="直达评论"><i class="fas fa-comments"></i></a><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="local-search"><div class="search-dialog"><div class="search-dialog__title" id="local-search-title">本地搜索</div><div id="local-input-panel"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div></div><hr/><div id="local-search-results"></div><span class="search-close-button"><i class="fas fa-times"></i></span></div><div id="search-mask"></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="/js/tw_cn.js"></script><script src="https://cdn.jsdelivr.net/npm/instant.page/instantpage.min.js" type="module"></script><script src="https://cdn.jsdelivr.net/npm/vanilla-lazyload/dist/lazyload.iife.min.js"></script><script src="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.js"></script><script src="/js/search/local-search.js"></script><div class="js-pjax"><script>function loadValine () {
  function initValine () {
    const valine = new Valine(Object.assign({
      el: '#vcomment',
      appId: 'ClIyIUhj1ue2rcRTsApYCR50-gzGzoHsz',
      appKey: 'ATug9IScYQBHILhKWEqBHYxM',
      placeholder: '昵称填入QQ号能获取到QQ头像哦~请输入正确的邮箱地址，你将会快速收到我的回复并且通过邮件通知你！~',
      avatar: 'robohash',
      meta: 'nick,mail,link'.split(','),
      pageSize: '10',
      lang: 'zh-cn',
      recordIP: false,
      serverURLs: 'https://cliyiuhj.lc-cn-n1-shared.com',
      emojiCDN: '',
      emojiMaps: "",
      enableQQ: true,
      path: window.location.pathname,
      requiredFields: ["nick,mail"],
      visitor: false
    }, null))
  }

  if (typeof Valine === 'function') initValine() 
  else getScript('https://cdn.jsdelivr.net/npm/valine/dist/Valine.min.js').then(initValine)
}

if ('Valine' === 'Valine' || !true) {
  if (true) btf.loadComment(document.getElementById('vcomment'),loadValine)
  else setTimeout(loadValine, 0)
} else {
  function loadOtherComment () {
    loadValine()
  }
}</script></div><script defer="defer" id="ribbon" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/canvas-ribbon.min.js" size="150" alpha="0.6" zIndex="-1" mobile="false" data-click="true"></script><script defer="defer" id="fluttering_ribbon" mobile="false" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/canvas-fluttering-ribbon.min.js"></script></div></body></html>